package com.emcom.gotour.validation;

import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

public class MultipartFileValidator implements InitializingBean {

	private final static long MAX_SIZE = 1024 * 1024;

	/**
	 * 文件大小上限
	 */
	private long maxSize = MAX_SIZE;

	/**
	 * 可接受的文件content-type
	 */
	private List<String> allowedContentTypes;

	public void validate(MultipartFile file) throws Exception {
		Assert.notNull(file, "The multipart file is null!");
		if(file.getSize() > maxSize) {
			System.out.println("file's size is invalid : " + file.getSize());
			throw new FileOutOfMaxLengthException("The file uploaded is out of max file size " + maxSize + " !");
		}
		if(!ArrayUtils.contains(allowedContentTypes.toArray(), file.getContentType())) {
			System.out.println("file's type is invalid : " + file.getContentType());
			throw new ContentTypeNotSupportException("The content type '"+file .getContentType()+"' is not a valid content type !");  
		}
	}

	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

	public void setAllowedContentTypes(List<String> allowedContentTypes) {
		this.allowedContentTypes = allowedContentTypes;
	}

	public void afterPropertiesSet() throws Exception {
		Assert.notEmpty(allowedContentTypes, "The content types allowed to be uploaded must contain one at least!");
	}

}
